package models;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

import com.trackvoodoo.models.RaceTracksDocument.RaceTracks;
import com.trackvoodoo.models.TrackDocument.Track;
import com.trackvoodoo.models.TrackDocument.Track.TrackDays;
import com.trackvoodoo.models.TrackPictureDocument.TrackPicture;

import database.connector.DatabaseFactory;
import database.live.DOAStatements;
import database.live.MySqlDAO;

public class TrackModel {

	private MySqlDAO d = null;
	private PreparedStatement p = null;
	RaceTracks tracks = null;
	
	public TrackModel()	
	{
		d = (MySqlDAO) DatabaseFactory.getDAO();
		if (d.isOpen())
		{
			try{
				tracks = RaceTracks.Factory.newInstance();
				ResultSet rs = d.selectQuery(DOAStatements.SELECT_TRACKS);
				while (rs.next())
				{
					Track t = tracks.addNewTrack();
					int id = rs.getInt(1);
					t.setId(id);
					t.setName(rs.getString(2));
					t.setDescription(rs.getString(3));
					
					//Now get the pictures trackOverview, location, picture
					p = d.getPreparedStatement(DOAStatements.SELECT_TRACKS_TRACKPICS);
					p.setInt(1, id);
					ResultSet rsPics = p.executeQuery();
					while (rsPics.next())
					{
						TrackPicture pic = t.addNewTrackPicture();
						pic.setTrackOverview(rsPics.getString(1));
						pic.setLocation(rsPics.getString(2));
						pic.setPicture(rsPics.getString(3));
					}
				
					//Now get the trackdates for this track date, description
					p = d.getPreparedStatement(DOAStatements.SELECT_TRACKS_TRACKDAYS);
					p.setInt(1, id);
					ResultSet rsTracks = p.executeQuery();
					while (rsTracks.next())
					{
						TrackDays tDay = t.addNewTrackDays();
						Date date = rsTracks.getDate(1);
						Calendar cal=Calendar.getInstance();
						cal.setTime(date);
						tDay.setDate(cal);
						tDay.setDesc(rsTracks.getString(2));
					}						
				}
			
			}catch (SQLException e)
			{
				
			}finally
			{
				d.closeConnection();
			}
		}
		
	}
	
	
	public RaceTracks getTracks()
	{
		return tracks;
	}
}
